// src/services/WebSocketService.ts
class WebSocketService {
    private socket: WebSocket | null = null;

    public connect(url: string): Promise<Event> {
        return new Promise((resolve, reject) => {
            this.socket = new WebSocket(url);

            this.socket.onopen = (event) => {
                this.socket.send("hello");
                console.log('WebSocket Open:', event);
                resolve(event);
            };

            this.socket.onerror = (event) => {
                console.error('WebSocket Error:', event);
                reject(event);
            };

            this.socket.onmessage = (event) => {
                console.log('WebSocket Message:', event.data);
                this.onMessage(event.data);
            };

            this.socket.onclose = (event) => {
                console.log('WebSocket Closed:', event);
            };
        });
    }

    public send(data: string): void {
        if (this.socket) {
            this.socket.send(data);
        }
    }

    public close(): void {
        if (this.socket) {
            this.socket.close();
        }
    }

    public onMessage(data: string): void {
        // Override this method in a subclass, or modify this method to handle messages.
        console.log('Received data:', data);
    }
}

export default WebSocketService;
